package com.ruoyi.business.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AntMerchantExpandIndirectZftSimplecreateModel;
import com.alipay.api.domain.ContactInfo;
import com.alipay.api.domain.DefaultSettleRule;
import com.alipay.api.domain.SiteInfo;
import com.alipay.api.request.AntMerchantExpandIndirectZftSimplecreateRequest;
import com.alipay.api.request.AntMerchantExpandIndirectZftorderQueryRequest;
import com.alipay.api.response.AlipayTradeMergePrecreateResponse;
import com.alipay.api.response.AlipayTradeWapMergePayResponse;
import com.alipay.api.response.AntMerchantExpandIndirectZftSimplecreateResponse;
import com.alipay.api.response.AntMerchantExpandIndirectZftorderQueryResponse;
import com.ruoyi.business.domain.TAliZftMerchantInfo;
import com.ruoyi.business.domain.TIsvInfo;
import com.ruoyi.business.service.AliZftPayToolService;
import com.ruoyi.business.service.ITAliZftMerchantInfoService;
import com.ruoyi.business.service.ITIsvInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AliZftPayToolServiceImpl implements AliZftPayToolService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ITIsvInfoService itIsvInfoService;

    @Autowired
    private ITAliZftMerchantInfoService itAliZftMerchantInfoService;
    @Override
    public AntMerchantExpandIndirectZftSimplecreateResponse AntMerchantExpandIndirectZftSimplecreate(TAliZftMerchantInfo tAliZftMerchantInfo) throws Exception {
        TIsvInfo isvInfo = itIsvInfoService.selectTIsvInfoById(Long.valueOf(tAliZftMerchantInfo.getIsvId()));
        AlipayClient alipayClient = getAliConfig(isvInfo);
        AntMerchantExpandIndirectZftSimplecreateRequest request = new AntMerchantExpandIndirectZftSimplecreateRequest();
        AntMerchantExpandIndirectZftSimplecreateModel model = new AntMerchantExpandIndirectZftSimplecreateModel();

        // 设置补充证件图片
//        model.setAdditionalCertImage("c6c0c7a1-b9d5-4e5d-b9d4-9eed39f00e65.jpg");

        // 设置经营地址
//        AddressInfo businessAddress = new AddressInfo();
//        businessAddress.setAddress("万塘路18号黄龙时代广场B座");
//        businessAddress.setDistrictCode("371002");
//        businessAddress.setLatitude("60.270001");
//        businessAddress.setCityCode("371000");
//        businessAddress.setPoiid("B0FFIVU189");
//        businessAddress.setProvinceCode("370000");
//        businessAddress.setType("BUSINESS_ADDRESS");
//        businessAddress.setLongitude("120.760001");
//        model.setBusinessAddress(businessAddress);

        // 设置补充证件类型
//        model.setAdditionalCertType("201");
        String externalId = RandomUtil.randomNumbers(15);
        // 设置商户编号
        model.setExternalId(externalId);

        // 设置商户站点信息
        SiteInfo sites = new SiteInfo();
        sites.setIcpOrgName(tAliZftMerchantInfo.getName());
        sites.setSiteType(tAliZftMerchantInfo.getSiteType());
//        sites.setSiteDomain("www.alipay.com");
//        sites.setScreenshotImage("c6c0c7a1-b9d5-4e5d-b9d4-9eed39f00e65.jpg");
//        sites.setRemark("备注说明");
//        sites.setAuthLetterImage("c6c0c7a1-b9d5-4e5d-b9d4-9eed39f00e65.jpg");
        sites.setSiteName(tAliZftMerchantInfo.getSiteName());
//        sites.setMarket("豌豆荚");
//        sites.setPassword("测试密码");
//        sites.setDownload("https://itunes.apple.com/cn/app/id333206289?mt=8");
//        sites.setTinyAppId("2021004105652035");
        sites.setSiteUrl(tAliZftMerchantInfo.getSiteUrl());
//        sites.setIcpServiceName("支付宝");
//        sites.setRemarkImage("c6c0c7a1-b9d5-4e5d-b9d4-9eed39f00e65.jpg");
//        sites.setAccount("测试账号");
//        sites.setIcpNo("沪ICP备15027489号-2");
//        sites.setStatus("ONLINE");
        model.setSites(sites);

        // 设置商户类别码 mcc
        model.setMcc(tAliZftMerchantInfo.getMcc());

        // 设置商户联系人信息
        ContactInfo contactInfos = new ContactInfo();
//        contactInfos.setIdCardNo("110000199001011234");
//        contactInfos.setPhone("0571-85022088");
        contactInfos.setName(tAliZftMerchantInfo.getContactName());
        contactInfos.setMobile(tAliZftMerchantInfo.getContactMobile());
//        contactInfos.setEmail("user@domain.com");
        model.setContactInfos(contactInfos);

        // 设置门头照
//        model.setOutDoorImages("c6c0c7a1-b9d5-4e5d-b9d4-9eed39f00e65.jpg");

        // 设置开票资料信息
//        MerchantInvoiceInfo invoiceInfo = new MerchantInvoiceInfo();
//        invoiceInfo.setMailTelephone("057162288888");
//        invoiceInfo.setTaxPayerQualification("01");
//        invoiceInfo.setAddress("浙江省杭州市西湖区西溪路蚂蚁金服");
//        invoiceInfo.setAcceptElectronic(false);
//        invoiceInfo.setTelephone("057162288888");
//        invoiceInfo.setTitle("蚂蚁金服（杭州）信息技术有限公司");
//        invoiceInfo.setMailName("张三");
//        invoiceInfo.setAutoInvoice(true);
//        invoiceInfo.setTaxPayerValid("19981011");
//        invoiceInfo.setTaxNo("51010482542598631219");
//        invoiceInfo.setBankName("中国银行");
//        AddressInfo mailAddress = new AddressInfo();
//        mailAddress.setAddress("万塘路18号黄龙时代广场B座");
//        mailAddress.setDistrictCode("371002");
//        mailAddress.setLatitude("60.270001");
//        mailAddress.setCityCode("371000");
//        mailAddress.setPoiid("B0FFIVU189");
//        mailAddress.setProvinceCode("370000");
//        mailAddress.setLongitude("120.760001");
//        invoiceInfo.setMailAddress(mailAddress);
//        invoiceInfo.setBankAccount("1234567812345678123");
//        model.setInvoiceInfo(invoiceInfo);

        // 设置商户行业资质图片
//        List<IndustryQualificationInfo> qualifications = new ArrayList<IndustryQualificationInfo>();
//        IndustryQualificationInfo qualifications0 = new IndustryQualificationInfo();
//        qualifications0.setIndustryQualificationImage("c6c0c7a1-b9d5-4e5d-b9d4-9eed39f00e65.jpg");
//        qualifications0.setIndustryQualificationType("B0099");
//        qualifications.add(qualifications0);
//        model.setQualifications(qualifications);
//
//        // 设置内景照
//        model.setInDoorImages("c6c0c7a1-b9d5-4e5d-b9d4-9eed39f00e65.jpg");

        // 设置交易场景
//        List<String> tradeScene = new ArrayList<String>();
//        tradeScene.add("WAP");
//        model.setTradeScene(tradeScene);

        // 设置结算支付宝账号
        model.setAlipayLogonId(tAliZftMerchantInfo.getAlipayLogonId());

        // 设置补充证件号
//        model.setAdditionalCertNo("9133010608210550XR");

        // 设置二级商户与服务商的签约时间
//        model.setSignTimeWithIsv("2015-04-15");

        // 设置（平替原来的oversea_settle_open_id字段
//        model.setOverseaSettleOpenId("074a1CcTG1LelxKe4xQC0zgNdId0nxi95b5lsNpazWYoCo5");

        // 设置商户别名
        model.setAliasName(tAliZftMerchantInfo.getAliasName());

        // 设置默认结算规则
        DefaultSettleRule defaultSettleRule = new DefaultSettleRule();
        defaultSettleRule.setDefaultSettleType(tAliZftMerchantInfo.getDefaultSettleType());
        defaultSettleRule.setDefaultSettleTarget(tAliZftMerchantInfo.getDefaultSettleTarget());
        model.setDefaultSettleRule(defaultSettleRule);

        // 设置（平替原来的info_source_uid字段
//        model.setInfoSourceOpenId("074a1CcTG1LelxKe4xQC0zgNdId0nxi95b5lsNpazWYoCo5");

        // 设置授权函
//        model.setLicenseAuthLetterImage("c6c0c7a1-b9d5-4e5d-b9d4-9eed39f00e65.jpg");

        // 设置商户客服电话
//        model.setServicePhone("0571-85022088");

        // 设置结算银行卡信息
//        SettleCardInfo bizCards = new SettleCardInfo();
//        bizCards.setAccountInstName("招商银行");
//        bizCards.setBankCode("103290003044");
//        bizCards.setAccountType("DC");
//        bizCards.setUsageType("01");
//        bizCards.setAccountHolderName("张三");
//        bizCards.setAccountInstCity("杭州市");
//        bizCards.setAccountInstId("CMB");
//        bizCards.setAccountNo("6214855710610408");
//        bizCards.setAccountInstProvince("浙江省");
//        bizCards.setAccountBranchName("招商银行杭州高新支行");
//        model.setBizCards(bizCards);

        // 设置商户使用服务
        List<String> service = new ArrayList<String>();
        service.add(tAliZftMerchantInfo.getService());
        model.setService(service);

        // 设置代扣产品信息
//        ZFTWithholdingInfo zftWithholdingInfo = new ZFTWithholdingInfo();
//        zftWithholdingInfo.setWithholdingServiceFeatureName("GENERAL_WITHHOLDING_P");
//        zftWithholdingInfo.setSignScene("DEFAULT");
//        model.setZftWithholdingInfo(zftWithholdingInfo);

        // 设置签约支付宝账户
        model.setBindingAlipayLogonId(tAliZftMerchantInfo.getBindingAlipayLogonId());

        // 设置（已废弃
//        model.setInfoSourceUid("2088111122223333");

        // 设置进件的二级商户名称
        model.setName(tAliZftMerchantInfo.getName());

        // 设置（已废弃
//        model.setOverseaSettleAccount("2088111122223333");

        request.setBizModel(model);
        AntMerchantExpandIndirectZftSimplecreateResponse response = alipayClient.certificateExecute(request);
        logger.info(response.getBody());
        if (response.isSuccess()) {
            tAliZftMerchantInfo.setOrderId(response.getOrderId());
            itAliZftMerchantInfoService.updateTAliZftMerchantInfo(tAliZftMerchantInfo);
        }else{
            throw new RuntimeException(response.getMsg()+":"+response.getSubMsg());
        }
        return response;
    }

    @Override
    public AntMerchantExpandIndirectZftorderQueryResponse AntMerchantExpandIndirectZftorderQuery(TAliZftMerchantInfo tAliZftMerchantInfo) throws Exception {
        TIsvInfo isvInfo = itIsvInfoService.selectTIsvInfoById(Long.valueOf(tAliZftMerchantInfo.getIsvId()));
        AlipayClient alipayClient = getAliConfig(isvInfo);
        AntMerchantExpandIndirectZftorderQueryRequest request = new AntMerchantExpandIndirectZftorderQueryRequest();
        request.setBizContent("{" +
                "  \"order_id\":\""+tAliZftMerchantInfo.getOrderId()+"\"" +
                "}");
        AntMerchantExpandIndirectZftorderQueryResponse response = alipayClient.certificateExecute(request);
        return response;
    }

    @Override
    public AlipayTradeMergePrecreateResponse AlipayTradeMergePrecreate() {
        return null;
    }

    @Override
    public AlipayTradeWapMergePayResponse AlipayTradeWapMergePay() {
        return null;
    }


    private AlipayClient getAliConfig(TIsvInfo isvInfo) throws AlipayApiException {
        String appCertPath = isvInfo.getIsvAppPublicPath();//"/Users/mac/Documents/WORK/场景/直付通11/appCertPublicKey_2021003196668931.crt";
        // 支付宝公钥证书路径
        String alipayCertPath = isvInfo.getIsvAliPublicPath();//"/Users/mac/Documents/WORK/场景/直付通11/alipayCertPublicKey_RSA2.crt";
        // 支付宝根证书路径
        String alipayRootCertPath = isvInfo.getIsvAliRootPath();//"/Users/mac/Documents/WORK/场景/直付通11/alipayRootCert.crt";

        // 应用APPID
        String appId = isvInfo.getIsvAppId();//"2021003196668931";
        // 初始化SDK
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        //设置应用Id
        certAlipayRequest.setAppId(appId);
        //设置应用私钥
//        certAlipayRequest.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCYjCsmZsld84YkTStL/AATrGzCmSLb6J4FZGV4eYSZWdGhsPDf3XEzCMTL/g3WvDNIISGiVek2NYXGKqy6VMdKHoS+miypmJVZ3EkgPwj/0hJWeyrKvWFn1nIUeW8u7mnJ7KJl51Opaj/+RUtkGWHKxOrBCY5KT2q7hiUTszuLCt23muU8dF9nxL9Kc+x6NgtPhj/oGdJNgQZMdjBqvshZ06oVoHcWDzK+zJJmft4YI+Km1+Uvcyk5ZtPDFXaqeFuSCUPBdRHq9AdoUG/CW1Xy0xVcICAZnI0SzuhKH9eEhyuLQ8yKHp8kajzXTxCUgKU5qI8wQmI2YiupVdQ+HqhDAgMBAAECggEAUcxnnvHi7HQW7ARNQTNhvyroLvj6jj0P7whEuPNAPRLCrBc7Mm+Fsb3z+QbD2O+V+Al8BZZXtW/Byd88O7YWHxJ6T9JQPKjK/SJ4O8hRRQwaNTFaYthmEM4W4g+zpNDG/TXcZxRB8kg9BFWX9Zb+r0IkN1quZ/5p1yA5ZXToaseW53da2N7TESXvrEGj4wQ91iHbRKVkCQGJBOPWuxKvmwU8h1NzpvQ4c1O/ZTuOmYzdBpNOVmNh5po1UGOkBYAMudh04X1CNBiSMkhrORe7Pw3grrOSyARSfutvQthww/xQ4JqHpi353gCPXwl22PXjUBRwXRKvaZM43w7h85vC4QKBgQDHSGI3j8Fes+HNhb/PXTETG1e4BFH1XQJgGXICOe5f4+Yi7Ih5KJrUu5xpD95/lYHqfnkXJhAzKFhcnCN8/3pol9af1WZU74XPjVmhE5pm1NoBjxqTFiS4g74TsGrCr3meE7C0fHuEL50LEJ+gzUhynKqjbir/j2fzHw/BiLYOKwKBgQDD9q+1aMsZ4QA1Xohu9bXHP2rD7UZzvrqD06rjEFuKnRWcob5afADKwx/wvlMucARPHMGMy/4uoBlDE5cLVRcFgq0Id2JiO9JpBWLJBMeEWKpF5ql9fEjayRiunaSt0rMKc6jjVfZxOOGrSdGlhZfjT9kwJpkyGtu5RhrhwGzaSQKBgG0twemQz68TvBT+PtzbwKQoKcG+VCyp/UArEKQZmvhcAlyF3CsMzO7ZrlJ9CDg778ZJ7gt5pgxxASATxvmXejfNYB+HKZ5E77mLRlySQdguqxWJklSdIBcazks5LvRkcKvjO79WJ9F+yHokbGALt7JbFL2fAN2scpXnIZm1TZCrAoGBAKqIWpA8CcMTkuLeyUwGd5JVFcw7CDxhll5yLRw8d+1AljYga07C6s2I0Jroheq7gIR4OdcVDrX0jQdaXO93tPkOpxXfDrb96DWMglL83cPGhScffA+/wIbkyZ3rggvid/x4elibzkLphTlSnCa3A17FdfP5Iwf/Z4bsAyjCE/hBAoGAP3e6umlHA/YSvULwK8W+5+CSql8tfMcycn7+IzZb8x4E5mwMERyViUBPTtLD+96HpLvNgiCtGTi+N0i0xa3mxyrOJwIvnKawCrHjO44wrtW59XLD6Ns8J2VxW9BYuGNFJ7SU+PXJ5nVNhdC9USLs9B7agLOJ9mOmNWCRuW1Jvrs=");
        certAlipayRequest.setPrivateKey(isvInfo.getIsvAliPrivateKey());

        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset("UTF-8");
        //设置签名类型
        certAlipayRequest.setSignType("RSA2");
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(appCertPath);
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipayCertPath);
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipayRootCertPath);
        //构造client
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        return alipayClient;
    }
}
